#!/usr/bin/ruby
# -*- ruby -*-
#
# http://www.reddit.com/r/dailyprogrammer/comments/z6o4k/9012012_challenge_94_easy_elemental_symbols_in/

require 'set'

_elements = %w{
  H  He  Li  Be   B   C   N   O   F  Ne  Na  Mg  Al  Si   P   S
 Cl  Ar   K  Ca  Sc  Ti   V  Cr  Mn  Fe  Co  Ni  Cu  Zn  Ga  Ge
 As  Se  Br  Kr  Rb  Sr   Y  Zr  Nb  Mo  Tc  Ru  Rh  Pd  Ag  Cd
 In  Sn  Sb  Te   I  Xe  Cs  Ba  La  Ce  Pr  Nd  Pm  Sm  Eu  Gd
 Tb  Dy  Ho  Er  Tm  Yb  Lu  Hf  Ta   W  Re  Os  Ir  Pt  Au  Hg
 Tl  Pb  Bi  Po  At  Rn  Fr  Ra  Ac  Th  Pa   U  Np  Pu  Am  Cm
 Bk  Cf  Es  Fm  Md  No  Lr  Rf  Db  Sg  Bh  Hs  Mt  Ds  Rg Uub
 Uut Uuq Uup Uuh Uuo}

elements = {}
_elements.each_with_index do |e, i|
  elements[e.downcase] = [e, i]
end

ARGV.each do |str|
  highlighted = Set.new

  (0 .. str.size).each do |i|
    # Generate substrings that may match
    s_1 = str.slice(i, 1)
    s_2 = str.slice(i, 2)
    s_3 = str.slice(i, 3)

    # Check matches - if the periodic table contains the element symbol as a substring,
    # replace *the first occurance* of it in the original string with the element
    # symbol highlighted
    highlighted << [str.gsub(s_1, "[#{elements[s_1].first}]"), s_1] if elements.has_key?(s_1)
    highlighted << [str.gsub(s_2, "[#{elements[s_2].first}]"), s_2] if elements.has_key?(s_2)
    highlighted << [str.gsub(s_3, "[#{elements[s_3].first}]"), s_3] if elements.has_key?(s_3)
  end

  # Sort the highlighted versions by atomic number of highlighted element symbol
  sorted = highlighted.to_a.sort do |a, b|
    elements[a.last].last <=> elements[b.last].last
  end

  # And print it
  sorted.each do |s|
    puts s.first
  end
end
